package uk.ac.aber.paws.server.autosleep;

import static uk.ac.aber.paws.server.config.Constants.*;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;

import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import uk.ac.aber.paws.client.core.PAWSClient;
import uk.ac.aber.paws.server.config.ConfigManager;
import uk.ac.aber.paws.server.core.PAWSServer;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 16th August 2011
 * 
 * SleepOperations.java
 * 
 * Contains all generic constants used within the application
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class SleepOperations {

	/**
	 * This function performs the required operations to remotely sleep a computer. It sends a
	 * message via a secure ServerSocket to the waiting client - handled by the PAWS client running on each client computer
	 * @param fqdn The computer name to receive the request
	 */
	public static void performSleepDownOnComputer(String fqdn) {
		
		try {
			
			SSLSocketFactory SSLSocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
			SSLSocket socket = (SSLSocket)SSLSocketfactory.createSocket(fqdn,Integer.parseInt(ConfigManager.getProperty("app.net.secureservercommsport")));
			
			final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
		    socket.setEnabledCipherSuites(enabledCipherSuites);
		   
		    // wait for a maximum of 2 seconds for a response
			socket.setSoTimeout(2000);
			
			// writing the command to the socket stream
			ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());             
			oos.writeObject(SLEEP_COMMAND); 
			
			oos.close();
		}
		catch ( Exception ex2) {
			PAWSServer.LOG_FILE.log(Level.ALL,"Problem sleeping "+fqdn+" via port 5688");
		}
	}

}


